package com.wsm.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsm.common.annotation.RedisCache;
import com.wsm.common.config.FilePathConfig;
import com.wsm.common.domain.FileDO;
import com.wsm.common.mapper.FileDao;
import com.wsm.common.service.FileService;
import com.wsm.common.utils.FileMapUtils;
import com.wsm.common.utils.FileUtil;
import com.wsm.common.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.List;
import java.util.Map;


@Service
public class FileServiceImpl extends ServiceImpl<FileDao, FileDO> implements FileService {
	@Autowired
	private FileDao sysFileMapper;

	@Autowired
	private FilePathConfig filePathConfig;

	@Autowired
	private FileDao fileDao;

	@Override
	@RedisCache(value = "file")
	public FileDO get(Long id){
		return sysFileMapper.get(id);
	}

	@Override
	@RedisCache(value = "file")
	public List<FileDO> list(Map<String, Object> map){
		return sysFileMapper.list(map);
	}

	@Override
	@RedisCache(value = "file")
	public int count(Map<String, Object> map){
		return sysFileMapper.count(map);
	}

	@Override
	@RedisCache(value = "file", flush = true)
	public boolean save(FileDO sysFile) {
		sysFile.setId(SnowFlake.nextId());
		if (sysFileMapper.insert(sysFile) > 0) {
			return true;
		}
		return false;
	}
	
	@Override
	@RedisCache(value = "file", flush = true)
	public int update(FileDO sysFile){
		return sysFileMapper.orUpdate(sysFile);
	}
	
	@Override
	@RedisCache(value = "file", flush = true)
	public int remove(Long id){
		return sysFileMapper.remove(id);
	}
	
	@Override
	@RedisCache(value = "file", flush = true)
	public int batchRemove(Long[] ids){
		return sysFileMapper.batchRemove(ids);
	}

    @Override
	@RedisCache(value = "file", flush = false)
    public Boolean isExist(String url) {
		Boolean isExist = false;
		if (!StringUtils.isEmpty(url)) {
			String filePath = url.replace("/files/", "");
			filePath = filePathConfig.getUploadPath() + filePath;
			File file = new File(filePath);
			if (file.exists()) {
				isExist = true;
			}
		}
		return isExist;
	}

	@Override
	public FileMapUtils downLoadFile(Long id){
		FileDO fileDO=fileDao.get(id);
		FileMapUtils fileMapUtils=null;
		try {
			fileMapUtils = FileUtil.downLoadFile(filePathConfig.getUploadPath(), fileDO.getUrl());
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
		return fileMapUtils;
	}
}
